package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.PetCategory;
import com.ruoyi.system.service.IPetCategoryService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 宠物分类Controller
 * 
 * @author ruoyi
 * @date 2025-08-30
 */
@RestController
@RequestMapping("/system/category")
public class PetCategoryController extends BaseController
{
    @Autowired
    private IPetCategoryService petCategoryService;

    /**
     * 查询宠物分类列表（树形结构）
     */
    @PreAuthorize("@ss.hasPermi('system:category:list')")
    @GetMapping("/list")
    public AjaxResult list(PetCategory petCategory)
    {
        List<PetCategory> list = petCategoryService.selectPetCategoryList(petCategory);
        List<PetCategory> treeList = petCategoryService.buildCategoryTree(list);
        return success(treeList);
    }

    /**
     * 查询顶级分类列表
     */
    @PreAuthorize("@ss.hasPermi('system:category:list')")
    @GetMapping("/listTopLevel")
    public AjaxResult listTopLevel()
    {
        List<PetCategory> list = petCategoryService.selectTopLevelCategories();
        return success(list);
    }

    /**
     * 根据父级ID查询子分类
     */
    @PreAuthorize("@ss.hasPermi('system:category:list')")
    @GetMapping("/listByParent/{parentId}")
    public AjaxResult listByParent(@PathVariable Long parentId)
    {
        List<PetCategory> list = petCategoryService.selectCategoriesByParentId(parentId);
        return success(list);
    }

    /**
     * 获取所有有效的宠物分类（用于下拉选择）
     */
    @GetMapping("/listActive")
    public AjaxResult listActive()
    {
        List<PetCategory> list = petCategoryService.selectActivePetCategories();
        return success(list);
    }

    /**
     * 获取分类及其名称列表（用于前端联动）
     */
    @GetMapping("/listWithNames")
    public AjaxResult listWithNames()
    {
        // 使用Service层的方法获取分类及其子分类的映射
        Map<String, List<String>> categoryNamesMap = petCategoryService.listCategoriesWithNames();
        
        // 转换为前端需要的格式
        Map<String, List<Map<String, String>>> result = new HashMap<>();
        
        for (Map.Entry<String, List<String>> entry : categoryNamesMap.entrySet()) {
            String categoryName = entry.getKey();
            List<String> subCategoryNames = entry.getValue();
            
            List<Map<String, String>> nameOptions = new ArrayList<>();
            for (String subCategoryName : subCategoryNames) {
                nameOptions.add(createNameMap(subCategoryName, subCategoryName));
            }
            
            // 如果没有子分类，则使用顶级分类作为默认名称
            if (nameOptions.isEmpty()) {
                nameOptions.add(createNameMap(categoryName, categoryName));
            }
            
            result.put(categoryName, nameOptions);
        }
        
        return success(result);
    }
    
    private Map<String, String> createNameMap(String value, String label) {
        Map<String, String> map = new HashMap<>();
        map.put("value", value);
        map.put("label", label);
        return map;
    }

    /**
     * 导出宠物分类列表
     */
    @PreAuthorize("@ss.hasPermi('system:category:export')")
    @Log(title = "宠物分类", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PetCategory petCategory)
    {
        List<PetCategory> list = petCategoryService.selectPetCategoryList(petCategory);
        ExcelUtil<PetCategory> util = new ExcelUtil<PetCategory>(PetCategory.class);
        util.exportExcel(response, list, "宠物分类数据");
    }

    /**
     * 获取宠物分类详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:category:query')")
    @GetMapping(value = "/{categoryId}")
    public AjaxResult getInfo(@PathVariable("categoryId") Long categoryId)
    {
        return success(petCategoryService.selectPetCategoryByCategoryId(categoryId));
    }

    /**
     * 新增宠物分类
     */
    @PreAuthorize("@ss.hasPermi('system:category:add')")
    @Log(title = "宠物分类", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PetCategory petCategory)
    {
        if (!petCategoryService.checkCategoryCodeUnique(petCategory))
        {
            return error("新增宠物分类'" + petCategory.getCategoryName() + "'失败，分类编码已存在");
        }
        petCategory.setCreateBy(getUsername());
        return toAjax(petCategoryService.insertPetCategory(petCategory));
    }

    /**
     * 修改宠物分类
     */
    @PreAuthorize("@ss.hasPermi('system:category:edit')")
    @Log(title = "宠物分类", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PetCategory petCategory)
    {
        if (!petCategoryService.checkCategoryCodeUnique(petCategory))
        {
            return error("修改宠物分类'" + petCategory.getCategoryName() + "'失败，分类编码已存在");
        }
        petCategory.setUpdateBy(getUsername());
        return toAjax(petCategoryService.updatePetCategory(petCategory));
    }

    /**
     * 删除宠物分类
     */
    @PreAuthorize("@ss.hasPermi('system:category:remove')")
    @Log(title = "宠物分类", businessType = BusinessType.DELETE)
    @DeleteMapping("/{categoryIds}")
    public AjaxResult remove(@PathVariable Long[] categoryIds)
    {
        return toAjax(petCategoryService.deletePetCategoryByCategoryIds(categoryIds));
    }
}